package com.umfwechat.lightprogram.controller.merchant;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.umfwechat.common.constant.CommonConsts;
import com.umfwechat.common.constant.ValueConsts;
import com.umfwechat.common.constant.PropertyConsts;
import com.umfwechat.common.prop.UmfPropModel;
import com.umfwechat.lightprogram.vo.StoreAccountQueryVo;
import com.umfwechat.util.DateTimesUtil;
import com.umfwechat.util.DesIDUtil;
import com.umfwechat.util.HttpUtil;
import com.umfwechat.util.PropertyUtil;
import com.umfwechat.util.RedisUtil;
import com.umfwechat.util.ReqMessageUtil;
import com.umpay.operation.common.RetCode;
import com.umpay.operation.model.qrConf.QrConf;
import com.umpay.operation.service.qrConf.remote.QrConfServiceRemote;
import com.umpay.sp.model.common.ReqMessage;
import com.umpay.sp.model.common.ResMessage;
import com.umpay.sp.model.saas.StoreInf;
import com.umpay.sp.model.settle.CollectSettleStat;
import com.umpay.sp.model.settle.SettleStat;
import com.umpay.sp.model.soopay.PayOrder;

import com.umpay.sp.service.saas.remote.StoreInfServiceRemote;
import com.umpay.sp.service.settle.remote.SettleStatServiceRemote;
import com.umpay.sp.util.StringUtil;
import com.umpay.sp.xml.XmlData;
import com.umpay.sp.service.soopay.remote.PayOrderDalServiceRemote;
import com.umpay.sp.service.soopay.remote.PayOrderServiceRemote;

@Controller
@RequestMapping("/mystore")
public class Mystore {
	private static Logger logger = LoggerFactory
			.getLogger(Mystore.class);
	@Resource
	private StoreInfServiceRemote storeInfServiceRemote;
	@Resource
	private QrConfServiceRemote qrConfServiceRemote;
	@Resource
	private SettleStatServiceRemote settleStatServiceRemote;	
	//订单
	@Resource
	private PayOrderServiceRemote payOrderServiceRemote;

	//订单
	@Resource
	private PayOrderDalServiceRemote payOrderDalServiceRemote;
	private int oneWeek = 7 * 24 * 60 * 60; //1周
	private String notifyUrl = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","notifyurl", "");	
	
	//查询店铺详情
	@RequestMapping(value = "/querystoreDetail", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject queryYesterdayMerTradeAmountBystores(HttpServletRequest req, HttpServletResponse resp) {
		JSONObject result=new JSONObject();
		//从前台获取参数
		String reqJSON=null;
		try {
			reqJSON = (String) req.getAttribute("_requestData");
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		JSONObject param=JSONObject.fromObject(reqJSON);
		String storeId =(String)param.get("storeId");
		if(StringUtil.isEmpty(storeId)){
			result.put("retCode","0001");
			result.put("retMsg", "商铺不能为空");
			return result;
		}
		
		//查询列表返回参数
		ResMessage detailResMsg = new ResMessage();
		//查询店铺列表请求参数
		ReqMessage detailReqMsg=ReqMessageUtil.makeSpReq();
		com.umpay.operation.common.ReqMessage detailReqMessage=ReqMessageUtil.makeOpReq();
		detailReqMsg.put("storeId", storeId);
		detailResMsg=storeInfServiceRemote.getStoreInfByPri(detailReqMsg);
		if(detailResMsg.getRetCode().equals("0000")){
			StoreInf storeInf=(StoreInf)detailResMsg.getValue(XmlData.STORE_INF);
	
//			//调用收款码查询接口  -注销
//			com.umpay.operation.common.ReqMessage qrReqMessage=ReqMessageUtil.makeOpReq();
//			qrReqMessage.put("merId", storeId);
//			com.umpay.operation.common.ResMessage qrResMessage=qrConfServiceRemote.queryQrConfByMerId(qrReqMessage);
//			List<String> qrCodeList=new ArrayList<String>();
//			if(qrResMessage.getRetCode().equals("0000")){
//				List<QrConf> qrConfList=(List<QrConf>)qrResMessage.getValue("qrList");
//				
//				if(qrConfList.size()>0){
//					for(int i=0;i<qrConfList.size();i++){
//						String qrCode=qrConfList.get(i).getQrId();
//						qrCodeList.add(qrCode);
//					}
//				}
//			}
			result.put("storeNickName", storeInf.getStoreShortName());
			result.put("storeName", storeInf.getStoreFullName());
			result.put("storeAddress",storeInf.getStoreFullAddr());
			result.put("storeRegion", storeInf.getStoreAddrProv() + "," + storeInf.getStoreAddrCity() + "," + storeInf.getStoreAddrArea());	//商户地址：省市区
			result.put("storeType",(storeInf.getStoreCategory()).replace("&", ","));	//商户类别
			result.put("payeeName",storeInf.getPayeeName());
			result.put("payeeMobile",storeInf.getPayeeMobileId());
			result.put("identity", DesIDUtil.desID2Star(storeInf.getPayeeInidcard()));	//收款人身份证号码
			result.put("userName",storeInf.getSalesmanId());
			result.put("labelOne", storeInf.getLabelOne());
			result.put("labelTwo", storeInf.getLabelTwo());
//			  result.put("qrCodeList", qrCodeList);
			result.put("agentId",storeInf.getAgentId());
			result.put("type",storeInf.getType());//入网方式
			//是否开pos报备编号
			String posReportId = storeInf.getPosReportId();
			String type = storeInf.getStoreType();//店铺类型
			String[] split = ValueConsts.OPEN_STORE_SUC_STATE2.split(CommonConsts.COMMA);//店铺状态区间
			List<String> list=Arrays.asList(split);
			if("0".equals(type)){//小微
				result.put("isOpenPos","2"); //没pos权限
			}else{
				if(list.contains(storeInf.getRegisterProcsState())){
					if(StringUtil.isEmpty(posReportId)){
						result.put("isOpenPos","0"); //没开通
					}else{
						result.put("isOpenPos","1");//已开通
					}
				}else{
					result.put("isOpenPos","2"); //没pos权限
				}
			}
			//获取代理商简称	
			logger.info("【调用查询当前代理商接口】");
			Map<String, Object> params = ReqMessageUtil.makeReqCrmMap();
			String adentId =storeInf.getAgentId();
			params.put("agentId",adentId);
			params.put("isQryMer", "0");
			Map<String, Object> crmResult = null;
			String retCode = "";
			Map<String, Object> agentMap  = null;
			try {
				XStream xstream = new XStream(new DomDriver());
				// URL配置文件取
				String url=UmfPropModel.INSTANCE.getPropValue("agent.crm.queryAgent");
				//调用受理注销用户标识接口
				logger.info("【查询当前代理商接口】入参：" + params);
				crmResult =  (Map<String, Object>) com.umfwechat.util.HttpUtil.getResObjPost(url, xstream, params);				
				logger.info("【查询当前代理商接口】出参：" + crmResult);		
				
				if(crmResult==null || crmResult.isEmpty()) {
					logger.info("==★====★★★★★★====★=查询当前代理商接口：请求CRM系统失败:查询当前代理商接口失败");				
					result.put(CommonConsts.RETCODE, "0001");
					result.put(CommonConsts.RETMSG,"服务器异常，请稍后再试");	
					return result;
				}
				retCode = (String) crmResult.get(CommonConsts.RETCODE);
				if (!RetCode.SUCCESS.equals(retCode)){
					logger.info("查询当前代理商接口失败!");
					result.put(CommonConsts.RETCODE, "0001");
					result.put(CommonConsts.RETMSG,"服务器异常，请稍后再试");	
					return result;
				}			
				agentMap =  (Map<String, Object>) crmResult.get("agentMap");
				if(agentMap.containsKey(adentId)){
					Map<String,String> agentDate = (Map<String,String>) agentMap.get(adentId);						
					result.put("agentName",agentDate.get("agentShortName"));
				}else{
					logger.info(" 查询当前代理商接口：没有此代理商的基本信息");
				}
			} catch (Exception e) {
				logger.error("【调用查询当前代理商接口失败!】",e);
				result.put(CommonConsts.RETCODE, "0001");
				result.put(CommonConsts.RETMSG,"服务器异常，请稍后再试");	
				return result;
			}		
			  result.put("retCode",RetCode.SUCCESS);
			  result.put("retMsg","获取成功");
			//店铺编号
			result.put("storeId", storeInf.getStoreId());
			//店铺状态
			result.put("registerProcsState", storeInf.getRegisterProcsState());
//			result.put("qrCodeList", qrCodeList);
			result.put("retCode",RetCode.SUCCESS);
			result.put("retMsg","获取成功");
		}else{
			result.put("retCode","0001");
			result.put("retMsg",detailResMsg.getRetMsg());
		}
			return result;
	}
	
	//绑定收款码
	@RequestMapping(value = "/bindQrCode", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject bindQrCode(HttpServletRequest req, HttpServletResponse resp) {
		JSONObject resMap=new JSONObject();
		resMap.put("retCode", "0000");
		resMap.put("retMsg", "绑定成功");
		//从前台获取参数
		String reqJSON=null;
		try {
			reqJSON = (String) req.getAttribute("_requestData");
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		JSONObject param=JSONObject.fromObject(reqJSON);
		String storeId =(String)param.get("storeId");
		String storeShortName =(String)param.get("storeShortName");
		List qrCodeList=(List)param.get("qrCodeList");
		List<String> qrCodes=new ArrayList<String>();
		for (int i = 0; i < qrCodeList.size(); i++) {
			com.umpay.operation.common.ReqMessage qrReqMessage=ReqMessageUtil.makeOpReq();
			qrReqMessage.put("qrId", qrCodeList.get(i));
			//调用收款码查询接口
			com.umpay.operation.common.ResMessage qrResMessage;
			try {
				qrResMessage=qrConfServiceRemote.queryQrConfByKey(qrReqMessage);
			} catch (Exception e) {
				resMap.put("retMsg", "服务器异常，请稍后再试");
				resMap.put("retCode", "0001");
				return resMap;
			}
			if(qrResMessage.getRetCode().equals("0000")){
				QrConf qrConf=(QrConf)qrResMessage.getValue("qrConf");
				logger.info(qrCodeList.get(i) + "绑定的商户为：" +qrConf);
				String merId = qrConf.getMerId();
				if("".equals(merId)){
					qrCodes.add(qrCodeList.get(i).toString());
					continue;
				}else if(storeId.equals(merId)){	//判断二维码是否是被该店铺绑定的
					continue;
				}else{
					resMap.put("retCode", "0001");
					resMap.put("retMsg",qrCodeList.get(i)+"已被其它商户绑定");
					return resMap;
				}
			}else{
				resMap.put("retMsg", qrCodeList.get(i) + "该收款码无效");
				resMap.put("retCode", "0001");
				return resMap;
			}
			
		}
		//绑定收款码
		for (String qrId : qrCodes) {
			com.umpay.operation.common.ReqMessage reqQrConf = ReqMessageUtil.makeOpReq();
			reqQrConf.put("qrId", qrId);
			reqQrConf.put("qrState", "1");
			reqQrConf.put("merId", storeId);
			reqQrConf.put("goodsName", "立马付");	//商品名称
			reqQrConf.put("merName", storeShortName);
			String notifyUrl = PropertyUtil.getStrValue("umfWeChatPlat_appConf.properties","notifyurl", "");	
			reqQrConf.put("notifyUrl", notifyUrl);	//回调路径
			
			com.umpay.operation.common.ResMessage resreqQrConf =null;
			try {
				resreqQrConf=qrConfServiceRemote.updateQrConfByQrId(reqQrConf);
			} catch (Exception e) {
				resMap.put("retCode", "0001");
				resMap.put("retMsg", qrId + "绑定失败");
				logger.info("根据主机查询收款码接口异常："+e);
				return resMap;
			}
			if(!resreqQrConf.getRetCode().equals("0000")){
				resMap.put("retCode", "0001");
				resMap.put("retMsg", qrId + "绑定失败");
				return resMap;
			}
		}
		return resMap;
	}
	//我的商户交易页面
	@RequestMapping(value = "/queryCurstoreTrade", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject queryCurstoreTrade(HttpServletRequest req, HttpServletResponse resp) {
		//JSONObject result=new JSONObject();
		//从前台获取参数
		String reqJSON=null;
		try {
			reqJSON = (String) req.getAttribute("_requestData");
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		JSONObject param=JSONObject.fromObject(reqJSON);
		
		/*String storeId="60000102";
		String pageSize="20";
		String pageNo="1";*/
		String storeId = (String)param.get("storeId");
		String pageSize = (String)param.get("pageSize");
		String pageNo =(String) param.get("pageNo");
		String posReportId = (String) param.get("posReportId");	//POS报备编号
		JSONObject resultJson = new JSONObject();
		List<String> payOrderList = new ArrayList<String>();
		
		if(StringUtil.isEmpty(storeId)){
			logger.info("店铺编号不能为空！"); 
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "店铺编号不能为空！");
			return resultJson;
		}
		if(StringUtil.isEmpty(pageSize) 
				|| Integer.parseInt(pageSize) == 0){
			logger.info("每页条数必须大于0！");
			resultJson.put("retCode",  "0001");
			resultJson.put("retMsg", "每页条数必须大于0！");
			return resultJson;
		}
		if(StringUtil.isEmpty(pageNo) 
				|| Integer.parseInt(pageNo) == 0){
			logger.info("当前页数必须大于0！");
			resultJson.put("retCode",  "0001");
			resultJson.put("retMsg", "当前页数必须大于0！");
			return resultJson;
		}
	
		int curPageNo = Integer.parseInt(pageNo);
		int curPageSize = Integer.parseInt(pageSize);
		
		try{
			String minDateStr = "";			
			//最近30天
			Calendar preMonthCalendar = Calendar.getInstance();
			preMonthCalendar.add(Calendar.DATE, -29);
			minDateStr = DateTimesUtil.date8(preMonthCalendar.getTime());
	
			//当前日期
			String currentDateStr =  DateTimesUtil.date8(Calendar.getInstance().getTime());
			String yesterdayDateStr = addDays(currentDateStr, -1);
			String endSettleDate = "";
			int loopCnt = 0;
			String currentPayOrderStr = "";	//今日订单
			String yesterdayPayOrderStr = "";	//昨日订单
			if(curPageNo == 1){
				//今天的统计，调用订单统计接口
				currentPayOrderStr = getPayOrderStr(posReportId, storeId, currentDateStr);
				if(StringUtil.isEmpty(currentPayOrderStr)){
					resultJson.put(CommonConsts.RETCODE, "0001");
					resultJson.put(CommonConsts.RETMSG, "订单统计失败！");
					return resultJson;
				}
				payOrderList.add(currentPayOrderStr);	//订单信息添加到日统计列表
				
				
				//昨天的统计，调用订单统计接口
				yesterdayPayOrderStr = getPayOrderStr(posReportId, storeId, yesterdayDateStr);
				if(StringUtil.isEmpty(yesterdayPayOrderStr)){
					resultJson.put(CommonConsts.RETCODE, "0001");
					resultJson.put(CommonConsts.RETMSG, "订单统计失败！");
					return resultJson;
				}
				payOrderList.add(yesterdayPayOrderStr);	//订单信息添加到日统计列表
				
				
				loopCnt = curPageSize - 2;
				endSettleDate = addDays(yesterdayDateStr, -1);
			}else{
				loopCnt = curPageSize;
				endSettleDate = addDays(currentDateStr, -(curPageNo-1) * loopCnt);
			}
			
			boolean redisNotExsitFlg = false;
			boolean maxViewFlg = false;
			
			for(int i=0; i<loopCnt; i++){
				//订单日期 --
				String orderDate = (i==0) ? endSettleDate : addDays(endSettleDate, -i);

				if(orderDate.compareTo(minDateStr) < 0){//订单日期<日期期限
					maxViewFlg = true;
					break;
				}
				
				
				String redisKey = "saasxcx" + storeId + orderDate;
				String payOrderStr = RedisUtil.get(redisKey);
				if(StringUtil.isEmpty(payOrderStr)){ //缓存中不存在
					redisNotExsitFlg = true;
					break;
				}
				//订单信息添加到日统计列表
				payOrderList.add(payOrderStr);
			}
			
			//最多能看 或者 缓存存在
	        if(maxViewFlg || !redisNotExsitFlg){
	        	logger.info("获取账单明细成功！");
	        	resultJson.put("retCode", RetCode.SUCCESS);
	        	resultJson.put("retMsg", "获取账单明细成功");
	        	resultJson.put("tradeList", payOrderList);
	    		return resultJson;
	        }
			
	        String startSettleDate =addDays(endSettleDate, -loopCnt + 1);
	        //结算查询(结算日期=交易日期+1)
	        Map<String, Object> qryMap = new HashMap<String, Object>();
			qryMap.put("merId", storeId);//商户编号
			qryMap.put("endDate", endSettleDate);//结束时间
			qryMap.put("startDate", startSettleDate);//开始时间
			qryMap.put("dealState", "2"); //处理完成
			List<SettleStat> settleStatList = settleStatServiceRemote.querySettleStats(qryMap);
			if(settleStatList == null || settleStatList.size() == 0){
				if(payOrderList.size()>0){
					logger.info("获取交易明细列表成功！");
					resultJson.put("retMsg", "获取交易明细列表成功");
				}else{
					logger.info("无账单明细！");
					resultJson.put("retMsg", "无账单明细！");
				}
				resultJson.put("retCode", RetCode.SUCCESS);
				resultJson.put("tradeList", payOrderList);
				return resultJson;
			}
			
			//初期化日统计列表
			payOrderList = new ArrayList<String>();
			if(!StringUtil.isEmpty(currentPayOrderStr)){
				payOrderList.add(currentPayOrderStr);	
			}
			if(!StringUtil.isEmpty(yesterdayPayOrderStr)){
				payOrderList.add(yesterdayPayOrderStr);	
			}
	
			//编辑输出列表
			for(int i=0; i<loopCnt; i++){
				boolean findFlg = false;
				String orderDate = (i==0) ? endSettleDate : addDays(endSettleDate, -i);
				if(orderDate.compareTo(minDateStr) < 0){
					break;
				}
				Map<String, Object> dataMap = new HashMap<String, Object>();
				for(SettleStat settleStat : settleStatList){
					//交易日期=结算日期-1
					if(orderDate.equals(settleStat.getSettleDate())){
						//结算金额+手续费+退费金额
						dataMap.put("date", orderDate.substring(0,4)+"-"+orderDate.substring(4,6)+"-"+orderDate.substring(6));//交易日期
						dataMap.put("storeSumAmount", settleStat.getAmount());//日总交易额
						dataMap.put("storeSumNum", settleStat.getTransNum());//日总笔数
						findFlg = true;
						break;
					}
				}
				
				if(!findFlg){
					dataMap.put("date",  orderDate.substring(0,4)+"-"+orderDate.substring(4,6)+"-"+orderDate.substring(6));//交易日期
					dataMap.put("storeSumAmount", 0);//日总交易额
					dataMap.put("storeSumNum", 0);//日总笔数
				}
				
				//添加到列表
				String payOrderStr = JSONObject.fromObject(dataMap).toString();
				payOrderList.add(payOrderStr);
				
				//存到缓存
				String redisKey = "saasxcx" + storeId + orderDate;
				RedisUtil.set(redisKey, oneWeek, payOrderStr);
			}
			
			resultJson.put("retCode", RetCode.SUCCESS);
			resultJson.put("retMsg", "获取交易明细列表成功");
			resultJson.put("tradeList", payOrderList);
			
			return resultJson;
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("获取账单明细失败",e);
			resultJson.put("retCode", "0001");
			resultJson.put("retMsg", "获取账单明细失败");
			return resultJson;
		}
		
	}
	//搜索页面
	@RequestMapping(value = "/querystoreByName", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject querystoreById(HttpServletRequest req, HttpServletResponse resp) {
		JSONObject result=new JSONObject();
		//从前台获取参数
		String reqJSON=null;
		try {
			reqJSON = (String) req.getAttribute("_requestData");
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		JSONObject param=JSONObject.fromObject(reqJSON);
		String content=(String)param.get("content");
		if(StringUtil.isEmpty(content)){
			result.put("retCode","0001");
			result.put("retMsg", "商户名称不能为空");
			return result;
		}
		//设置当前页
		String pageNo=(String)param.get("pageNo");
		if(StringUtil.isEmpty(pageNo)){
			pageNo="1";
		}
		int curPage=Integer.parseInt(pageNo);
		int pageSize=20;
	
	
		//设置昨天的日期
		
		Calendar cal=Calendar.getInstance();
		cal.add(Calendar.DATE, -1); 
		String yesterDay=DateTimesUtil.date8(cal.getTime());
		
		//查询店铺列表请求参数
		ReqMessage queryReqMsg=ReqMessageUtil.makeSpReq();
		if (!param.get("loginUserId").equals("admin")) {
			queryReqMsg.put("salesmanId",(String)param.get("loginUserId"));
		}
		queryReqMsg.put("agentId",(String)param.get("loginAgentId"));
		queryReqMsg.put("storeShortName", content);
		queryReqMsg.put("registerProcsStates","'06','07','08','09'");
		queryReqMsg.put("startNo",(curPage-1)*pageSize+"");
		queryReqMsg.put("endNo",curPage*pageSize+"");
		/*queryReqMsg.put("salesmanId","Cfl");
		queryReqMsg.put("agentId","Y593075163");
		queryReqMsg.put("storeShortName","飞");
		
		queryReqMsg.put("startNo","0");
		queryReqMsg.put("endNo","2");*/
		
		ResMessage queryMsg=storeInfServiceRemote.getStoreInfList(queryReqMsg);
		if(queryMsg.getRetCode().equals("0000")){
			List<StoreInf> storeList=(List<StoreInf>)queryMsg.getValue(XmlData.STORE_INF_LIST);
			if(storeList.size()>0){
				StringBuilder sb=new StringBuilder();
				for(int i=0;i<storeList.size();i++){
					sb.append("'");
					sb.append(storeList.get(i).getStoreId());
					sb.append("'");
					sb.append(",");
				}
				//查询金额笔数汇总参数
				ReqMessage querySumReqMsg=ReqMessageUtil.makeSpReq();
				ResMessage querySumResMsg = new ResMessage();
				//设置汇总查询的参数
				querySumReqMsg.put(XmlData.START_DATE,yesterDay );
				querySumReqMsg.put(XmlData.END_DATE,yesterDay);
				querySumReqMsg.put(XmlData.MER_ID_S,sb.toString().substring(0,sb.toString().length()-1));
				//查询统计
				querySumResMsg=settleStatServiceRemote.collectSettleStatsByMerIdAndDate(querySumReqMsg);
				
				if(querySumResMsg.getRetCode().equals("0000")){
					List<CollectSettleStat> collectSettleStatList=
							(List<CollectSettleStat>)querySumResMsg.getValue(XmlData.COLLECT_SETTLE_STAT_LIST);
					List<StoreAccountQueryVo> sumList=new ArrayList<StoreAccountQueryVo>();
					for(int i=0;i<storeList.size();i++){
						StoreInf storInf=storeList.get(i);
						StoreAccountQueryVo saqVo=new StoreAccountQueryVo();
						saqVo.setStoreId(storInf.getStoreId());
						saqVo.setStoreName(storInf.getStoreShortName());
						saqVo.setCreateDate(DateTimesUtil.date10(storInf.getIntime()));
						int sumAmount=0;
						int sumNum=0;
						if(collectSettleStatList.size()>0){
							for(int j=0;j<collectSettleStatList.size();j++){
								String merId=collectSettleStatList.get(j).getMerId();
								if((storInf.getStoreId()).equals(merId)){
									String amount=collectSettleStatList.get(j).getAmount()==""?"0":collectSettleStatList.get(j).getAmount();
									sumAmount+=Integer.parseInt(amount);
									String loanNum=collectSettleStatList.get(j).getLoanNum()==""?"0":collectSettleStatList.get(j).getLoanNum();
									sumNum+=Integer.parseInt(loanNum);
								}
							}
						}
						saqVo.setSumAmount(sumAmount+"");
						saqVo.setSumNum(sumNum+"");
						sumList.add(saqVo);
					}
					result.put("retCode", querySumResMsg.getRetCode());
					result.put("retMsg",querySumResMsg.getRetMsg());
					result.put("storeList", sumList);
				}else{
					result.put("retCode", "0001");
					result.put("retMsg",querySumResMsg.getRetMsg());
					return result;
				}
			}else{
				result.put("retCode", "0010");
				result.put("retMsg","商铺列表为空");
			}
		}else{
			result.put("retCode","0001");
			result.put("retMsg", queryMsg.getRetMsg());
		}
		
		return result;
	}
	/**
	 * 每日交易列表
	 * @param req
	 * @param resp
	 * @return
	 */
	@RequestMapping(value = "/queryCurDateTradeDetail", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject queryCurDateTradeDetail(HttpServletRequest req, HttpServletResponse resp) {
		JSONObject result=new JSONObject();
		//从前台获取参数
		String reqJSON=null;
		try {
			reqJSON = (String) req.getAttribute("_requestData");
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		JSONObject param=JSONObject.fromObject(reqJSON);
		logger.info("日交易明细列表查询接口 开始");
		String storeId =(String)param.get("storeId");
		String payType = (String)param.get("payType");
		String orderDateStr =(String) param.get("date");
		String currentPageStr = (String)param.get("pageNo");
		String pageSizeStr =(String)param.get("pageSize");
		if(payType == null || "".equals(payType) ){
			payType = "1,2,3";
		}
		String[] payList = payType.split(",");	
		List<String> tradeList = new ArrayList<String>();
		
		if(StringUtil.isEmpty(storeId)){
			logger.info("店铺编号不能为空！"); 
			result.put("retCode", "0001");
			result.put("retMsg", "店铺编号不能为空！");
			return result;
		}
		if(StringUtil.isEmpty(orderDateStr)){
			logger.info("交易日期不能为空！"); 
			result.put("retCode", "0001");
			result.put("retMsg", "交易日期不能为空！");
			return result;
		}
		if(StringUtil.isEmpty(pageSizeStr) 
				|| Integer.parseInt(pageSizeStr) == 0){
			logger.info("每页条数必须大于0！");
			result.put("retCode", "0001");
			result.put("retMsg", "每页条数必须大于0！");
			return result;
		}
		if(StringUtil.isEmpty(currentPageStr) 
				|| Integer.parseInt(currentPageStr) == 0){
			logger.info("当前页数必须大于0！");
			result.put("retCode", "0001");
			result.put("retMsg", "当前页数必须大于0！");
			return result;
		}
		
		try{
			StringBuilder productIdSb = new StringBuilder();
            if(payList == null || payList.length == 0
            		|| (payList.length == 1 && Integer.parseInt(payList[0]) == 0)){
            	//立马付-微信
            	productIdSb.append(PropertyConsts.PRODUCTID_WECHAT);
            	//立马付-支付宝
            	productIdSb.append(",").append(PropertyConsts.PRODUCTID_ALIPAY);
            	//微信公众号支付
            	productIdSb.append(",").append(PropertyConsts.PRODUCTID_WECHATPAY);
            }else{
            	for(int i=0;i<payList.length;i++){
            		if(i > 0){
            			productIdSb.append(",");
            		}
            		int type = Integer.parseInt(payList[i]);
            		if(type == 1){//立马付-微信
                		productIdSb.append(PropertyConsts.PRODUCTID_WECHAT);
                    }else if(type == 2){//立马付-支付宝
                    	productIdSb.append(PropertyConsts.PRODUCTID_ALIPAY);
                    }else if(type == 3){//微信公众号支付
                    	productIdSb.append(PropertyConsts.PRODUCTID_WECHATPAY);
                    }
                }
            }
			ReqMessage reqMessage = ReqMessageUtil.makeSpReq();
			reqMessage.getReqMap().put("merId", storeId);
			reqMessage.getReqMap().put("startDate",changeDateFomate(orderDateStr));
			reqMessage.getReqMap().put("endDate", changeDateFomate(orderDateStr));
			reqMessage.getReqMap().put("currentPage",currentPageStr);
			reqMessage.getReqMap().put("pageSize", pageSizeStr);
			reqMessage.getReqMap().put("orderStateList", "2,4");
			reqMessage.getReqMap().put("productIdList", productIdSb.toString());
			//订单查询
			/*SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");*/
			logger.info("【获取每日交易列表】入参" + reqMessage);
			ResMessage resMessage = payOrderDalServiceRemote.queryPayOrderListDesc(reqMessage);
			logger.info("【获取每日交易列表】出参" + resMessage);
			if(resMessage.getRetCode().equals(RetCode.SUCCESS)){
				List<PayOrder> payOrders = (List<PayOrder>)resMessage.getValue(XmlData.RESULT_LIST);
				for(PayOrder payOrder : payOrders){
					Map<String, Object> dataMap = new HashMap<String, Object>();
					dataMap.put("dateTime", DateTimesUtil.datetime15(payOrder.getInTime()));
					dataMap.put("amount", payOrder.getAmount()+"");
					
					String productId = payOrder.getProductId();
					if(PropertyConsts.PRODUCTID_WECHAT.indexOf(productId) >= 0){//立马付-微信
						dataMap.put("paymentUserName", "微信用户");
						dataMap.put("payType", 1);
					}else if(PropertyConsts.PRODUCTID_ALIPAY.indexOf(productId) >= 0){//立马付-支付宝
						dataMap.put("paymentUserName", "支付宝用户");
						dataMap.put("payType", 2);
					}else if(PropertyConsts.PRODUCTID_WECHATPAY.indexOf(productId) >= 0){//微信公众号支付
						dataMap.put("paymentUserName", "微信用户");
						dataMap.put("payType", 3);
					}else{
						dataMap.put("paymentUserName", "");
						dataMap.put("payType", null);
					}
					dataMap.put("tradeNo", payOrder.getTradeNo());
					tradeList.add(JSONObject.fromObject(dataMap).toString());
				}
				logger.info("获取日交易列表成功！");
	        	result.put("retCode", RetCode.SUCCESS);
	    		result.put("retMsg", "获取日交易列表成功！");
			}else{
				logger.info("订单查询信息失败！");
	        	result.put("retCode", "0001");
	    		result.put("retMsg", "订单查询信息失败！");
			}
			
			result.put("tradeList", tradeList);
    		return result;
			
		} catch (Exception e) {
			logger.info("获取日交易列表失败",e);
			result.put("retCode","0001");
			result.put("retMsg", "获取日交易列表失败");
			return result;
		}
	} 
	public static String addDays(String dateStr, int days){
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.YEAR, Integer.parseInt(dateStr.substring(0, 4)));
		calendar.set(Calendar.MONTH, Integer.parseInt(dateStr.substring(4, 6))-1);
		calendar.set(Calendar.DATE, Integer.parseInt(dateStr.substring(6, 8)));
		calendar.add(Calendar.DATE, days);
        return DateTimesUtil.date8(calendar.getTime());
	}
	public String changeDateFomate(String curDate){
		return curDate.substring(0,4)+curDate.substring(5,7)+curDate.substring(8);
	}
	
	
/**
 * *****************************
 * 以下方法直接从公众号类中复制过来（BillDetailController）
 * 直接复制就行START
 * *****************************
 */
	
	/**
	 * 订单统计
	 * 
	 * @param posReportId 报备编号
	 * @param storeId 店铺编号
	 * @param orderDate 交易日期
	 * @return
	 * @throws Exception
	 */
	private String getPayOrderStr(String posReportId, String storeId, String orderDate) throws Exception{
		
		ReqMessage reqMessage = ReqMessageUtil.makeSpReq();
		reqMessage.put(CommonConsts.QRYTYPE, "1"); //查询类型
		reqMessage.put(CommonConsts.MERID, storeId); //商户编号
		reqMessage.put(CommonConsts.ORDERDATE, orderDate);//订单日期
		logger.info("【订单统计】入参：" + reqMessage);
		ResMessage payOrderRes = payOrderServiceRemote.statPayOrder(reqMessage);
		logger.info("【订单统计】出参：payOrderRes=" + payOrderRes);
		if(!RetCode.SUCCESS.equals(payOrderRes.getRetCode())){
			logger.info("订单统计失败！" + payOrderRes.getRetMsg());
			return null;
		}
		 
		//pos金额
		String posAmt = "0";
		//pos笔数
		String posNum = "0";
		if(StringUtil.isNotEmpty(posReportId)){
			//获取pos的统计金额和笔数
			Map<String, Object> posDataMap = getPosAmtNum(storeId, orderDate);
			if(!RetCode.SUCCESS.equals(posDataMap.get(CommonConsts.RETCODE))){
				logger.info("商户交易统计查询失败！" + posDataMap.get(CommonConsts.RETMSG));
				return null;
			}
			//pos金额
			posAmt = posDataMap.get(CommonConsts.TRAN_AMTS).toString();
			//pos笔数
			posNum = posDataMap.get(CommonConsts.TRAN_COUNT).toString();
		}
		
		//订单金额
		String successAmt = payOrderRes.getValue(CommonConsts.SUCCESS_AMT).toString();
		//金额总计 = 订单金额+pos金额 
		String dealAmt = new BigDecimal(successAmt).add(new BigDecimal(posAmt)).toString();
		
		//订单笔数
		String successNum = payOrderRes.getValue(CommonConsts.SUCCESS_NUM).toString();
		//金额总计 = 订单笔数 +pos笔数
		int dealNum = Integer.parseInt(successNum) + Integer.parseInt(posNum);
				
		//订单信息
		Map<String,Object> dataMap =  new HashMap<String,Object>();
		//订单日期
		dataMap.put(CommonConsts.DATE, DateTimesUtil.date10(orderDate));
		//成功金额
		dataMap.put("storeSumAmount", dealAmt);
		//成功笔数
		dataMap.put("storeSumNum", dealNum);
		return JSONObject.fromObject(dataMap).toString();
	}
	/**
	 * 获取商户交易统计
	 * 
	 * @param storeId 店铺编号
	 * @param orderDate 交易日期
	 * @return
	 * @throws Exception
	 */
	private Map<String,Object> getPosAmtNum(String storeId, String orderDate) throws Exception{
		//商户交易统计查询接口 /offline-serv1/0903
		String url = UmfPropModel.INSTANCE.getPropValue("saas.pos.offlineserv10903");
		ReqMessage reqMessage = ReqMessageUtil.makeSpReq();
		Map<String, Object> reqMap = new HashMap<String, Object>();
		reqMap.put(CommonConsts.RPID, reqMessage.getRpid());
		reqMap.put(CommonConsts.REQDATE, reqMessage.getReqDate());
		reqMap.put(CommonConsts.REQTIME, reqMessage.getReqTime());
		//参数数据来源
		reqMap.put(CommonConsts.DATASOURCE, CommonConsts.SAAS);
		//商户号
		reqMap.put(CommonConsts.MERCHANTID, storeId);
		//交易日期
		reqMap.put(CommonConsts.LOCALSYSDATE, orderDate);
		
		Map<String, Object> dataMap = HttpUtil.httpPostForm2Xml(url, reqMap);
		
		return dataMap;
	}
/**
 * *****************************
 * 以上方法直接从公众号类中复制过来（BillDetailController）
 * 直接复制就行END
 * *****************************
 */
}
